/*
 * @Description: 条件们
 * @Author: Zzt
 * @Date: 2022-11-19 11:47:20
 * @LastEditTime: 2022-12-07 14:11:29
 */
import { Button, Checkbox, Popover } from 'antd';
import { CaretDownFilled } from '@ant-design/icons';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { CheckboxValueType } from 'antd/es/checkbox/Group';
import { useState } from 'react';

const CheckboxGroup = Checkbox.Group;

const MultiSelect = (props: any) => {
  console.log('propr', props);

  const { title, checkList, value, onChange } = props;
  /* 档案多选 */
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>(
    checkList.map((item: any) => item.value)
  );
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(true);

  const triggerChange = (changedValue: any) => {
    onChange?.(changedValue);
  };

  const onCheckAllChange = (event: CheckboxChangeEvent) => {
    setCheckedList(event.target.checked ? checkList.map((item: any) => item.value) : []);
    setIndeterminate(false);
    setCheckAll(event.target.checked);
    triggerChange(event.target.checked ? checkList.map((item: any) => item.value) : []);
  };

  const onChangeCheck = (list: []) => {
    console.log('list', list);
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < checkList.length);
    setCheckAll(list.length === checkList.length);
    triggerChange(list);
  };
  const content = () => {
    return (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
          全选
        </Checkbox>
        <CheckboxGroup
          options={checkList}
          value={checkedList || value?.checkedList}
          onChange={onChangeCheck}
          style={{ display: 'flex', flexDirection: 'column' }}
        />
      </div>
    );
  };
  return (
    <>
      <Popover placement="bottom" content={content} trigger="click">
        <Button type="text">
          {title}
          <CaretDownFilled />
        </Button>
      </Popover>
    </>
  );
};
export default MultiSelect;
